package com.zyy.game.tianlong.network.codec;

import com.zyy.game.tianlong.network.GameContext;
import com.zyy.game.tianlong.network.SocketMsg;
import com.zyy.game.tianlong.network.callback.GlobalExceptionCallBack;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * 解码器 将二进制转换为{@link SocketMsg}对象
 *
 * @author relufi
 * @date 2019/7/22 0022 10:23
 */
@ChannelHandler.Sharable
public class GameByteToMsgDecoder extends ChannelInboundHandlerAdapter {
    private final GlobalExceptionCallBack globalExceptionCallBack;

    public GameByteToMsgDecoder(GlobalExceptionCallBack globalExceptionCallBack) {
        this.globalExceptionCallBack = globalExceptionCallBack;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = ((ByteBuf) msg);
        SocketMsg socketMsg = new SocketMsg();
        byte[] bytes;
        try {
            socketMsg.setOpCode(in.readIntLE());
            socketMsg.setSubCode(in.readIntLE());
            bytes = new byte[in.readableBytes()];
            in.readBytes(bytes);
        } finally {
            in.release();
        }
        socketMsg.setData(new String(bytes, StandardCharsets.UTF_8));
        ctx.fireChannelRead(socketMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        globalExceptionCallBack.exceptionCaught(new GameContext(ctx), cause);
    }
}
